<template>
  <div class="login-wrapper">
    <!-- 积分规则说明 -->
    <div class="login-left">
      <div v-for="item in pointsList" class="login-left-every">
        <div>
          <a-image :src="item.src" :preview="false" style="width: 50px;height: 53px;" alt="image" />
        </div>
        <div class="left-letter">
          <h1>{{ item.title }}</h1>
          <p style="font-size: 20px;" v-if="item.title=='POINTS REDEMPTION'">
            1 points = {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(1) }}
          </p>
          <p style="font-size: 20px;" v-else>
            {{ item.desc }}
            <br>
            {{ item.desc1 }}
          </p>
        </div>
      </div>
    </div>
    <!-- 登录注册 -->
    <a-card class="login-card">
      <a-tabs v-model:activeKey="activeKey">

        <!-- 登录 -->
        <a-tab-pane key="1" tab="SIGN IN">
          <a-form :model="formState" name="login" :rules="rules" ref="formRef">
            <a-col :span="24" style="margin-top: 6px;">Email Address</a-col>
            <a-form-item name="username">
              <a-auto-complete placeholder="Email Address" v-model:value="formState.username"
                :options="savedEmails.map(email => ({ value: email, label: email }))" style="height: 44px;"
                allowClear />
            </a-form-item>
            <a-col :span="24" class="remember-email"><span style="margin-right: 5px;">Remember Email</span><a-checkbox
                v-model:checked="rememberEmail"></a-checkbox></a-col>

            <a-col :span="24">Your Password</a-col>
            <a-form-item name="password">
              <a-input-password v-model:value="formState.password" placeholder="Your Password" style="height: 44px;">
              </a-input-password>
            </a-form-item>


            <!-- 登录 -->
            <div class="sign-sty" @click="goPerson">SIGN IN</div>

            <!-- 忘记密码 -->
            <div class="login-forget" style="display: flex;justify-content: space-between">
              <a class="forgotten" @click="forget">Forgot your password?</a>
              <a class="forgotten" @click="cancelAccount">Cancel the account</a>
            </div>
          </a-form>
        </a-tab-pane>

        <!-- 注册 -->
        <a-tab-pane key="2" tab="JOIN US" force-render>
          <Register></Register>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted ,getCurrentInstance} from 'vue';
import { UserOutlined, LockOutlined, PhoneOutlined, ShoppingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { parsePhoneNumberFromString } from 'libphonenumber-js';
import { useUserStore } from '@/store/user';
import { login, sendVerificationCode } from '@/api/user';
import type { Rule } from 'ant-design-vue/es/form';
import type { LoginParams } from '@/api/user';
import PhoneNumberInput from '@/components/PhoneNumberInput.vue';
import { Local } from "@/utils/storage.ts";
import { setToken } from '@/utils/auth';
import Register from "@/views/Register.vue"
import { useCurrencyStore } from '@/store';

const { proxy } = getCurrentInstance()
const currencyStore = useCurrencyStore();
const activeKey = ref('1');
const router = useRouter();
const userStore = useUserStore();
const rememberMe = ref(false);
const isLoading = ref(false);
onMounted(() => {
  // 获取记住的邮箱数组
  savedEmails.value = JSON.parse(localStorage.getItem('rememberedEmails') || '[]');
  if (savedEmails.value.length > 0) {
    // 使用最后一个保存的邮箱
    formState.username = savedEmails.value[savedEmails.value.length - 1];
    rememberEmail.value = false;
  }
});
const rememberEmail = ref(false);
const savedEmails = ref<string[]>([]);
const formRef = ref();
const formState = reactive({
  username: '',
  password: '',
});
// 积分规则列表
const pointsList = ref([
  {
    title: 'EXCLUSIVE SALES&EVENTS',
    desc: 'Early access to new arrivals',
    desc1: "and exclusive offer during Members' Day",
    src: 'https://melov-net.oss-us-west-1.aliyuncs.com/upload/20250526181923/20250526181923_6834402b7186d.webp'
  },
  {
    title: 'BIRTHDAY GIFT',
    desc: 'Enjoy a $20 OFFER on your birthday',
    desc1: "",
    src: 'https://melov-net.oss-us-west-1.aliyuncs.com/upload/20250526181905/20250526181905_68344019b1a8f.webp'
  },
  {
    title: 'POINTS REDEMPTION',
    desc: '',
    desc1: "",
    src: 'https://melov-net.oss-us-west-1.aliyuncs.com/upload/20250526181934/20250526181934_68344036e29e3.webp'
  }
  , {
    title: 'EASY RETURN & EXCHANGE',
    desc: 'Enjoy up to 15 days return period',
    desc1: "",
    src: 'https://melov-net.oss-us-west-1.aliyuncs.com/upload/20250526181944/20250526181944_68344040bd27b.webp'
  }
])

const rules = {
  username: [
    { required: true, message: 'Please enter username', trigger: ['blur', 'change'] },
    { type: 'email', message: 'Please enter the correct username address', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: 'Please enter password', trigger: 'blur' },
    { min: 8, message: 'Password does not meet requirements', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z]).*$/,
      message: 'The password consists of at least eight characters, including uppercase and lowercase letters as well as numbers',
      trigger: 'blur'
    }
  ],
};

// 注销账号
const cancelAccount = () => {
  router.push('/cancelAccount')
}

// 忘记密码
const forget = () => {
  router.push('/forgetPassword')
}
// 登录
const goPerson = () => {
  formRef.value.validate().then(() => {
    login(formState).then((res) => {
      if (res.code == 200) {
        message.success('successfully login')
        try {
          // 先设置token和用户信息
          setToken(res.result.token);
          Local.set('refresh_token', res.result.refresh_token);
          
          // 等待用户信息加载完成
          userStore.setUserInfo(res.result);
          
          // 发送自定义事件通知其他组件登录状态已更新
          window.dispatchEvent(new CustomEvent('user-login-success'));
          
          // 登录成功后，如果勾选了记住邮箱，则保存
          if (rememberEmail.value) {
            const savedEmails = JSON.parse(localStorage.getItem('rememberedEmails') || '[]');
            if (!savedEmails.includes(formState.username)) {
              savedEmails.push(formState.username);
              localStorage.setItem('rememberedEmails', JSON.stringify(savedEmails));
            }
          }
          
          // 最后再跳转页面
          router.push({
            path: '/user/profile',
          })
        } catch (error) {
          message.error("Failed to load user info");
        }
      }
      formRef.value.resetFields()
    })
  })
    .catch(error => {
      console.log('error', error);
    });
}
</script>

<style scoped lang="scss">
.login-wrapper {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  min-height: 100vh;
  padding: 40px 0;
  background: linear-gradient(180deg, transparent, rgba(0, 0, 0, .6)), url(https://melov-net.oss-us-west-1.aliyuncs.com/upload/20250526183120/20250526183120_683442f8c2fa6.webp) 50% / cover, #d3d3d3 50% / cover no-repeat;
}

.login-left {
  width: 25%;
  color: #fff;
}

.login-left-every {
  display: flex;
  align-items: center;
  margin-bottom: 50px;
}

.left-letter {
  margin-left: 20px;
}

.login-card {
  width: 30%;
  /* max-width: 400px; */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  background-color: #ffffffe6;
  padding: 30px;
}

.login-form-forgot {
  float: right;
}

.form-footer {
  text-align: center;
  margin-top: 16px;
  color: #999;
}

.form-footer a {
  color: #1890ff;
  margin-left: 8px;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  margin-top: 0;
  margin-bottom: 0;
  font-weight: 500;
  font-size: 24px;
}

.remember-email {
  color: #000 !important;
  font-size: 12px !important;
  font-stretch: normal;
  font-style: normal;
  text-transform: uppercase !important;
  letter-spacing: normal;
  text-align: right;
}

.login-forget {
  a{
    color: #3c3c3c !important;
    font-size: 12px !important;
    font-stretch: normal;
    font-style: normal;
    /* text-transform: uppercase !important; */
    font-weight: 500;
    line-height: 1.67;
    letter-spacing: normal;
    text-align: center;
    margin-top: 20px;
    text-decoration: underline;
    cursor: pointer;
  }
}

.forgotten {}

.sign-sty {
  background-color: #b38654 !important;
  width: 258px;
  padding: 10px 0px;
  color: #fff;
  font-weight: 700 !important;
  margin: 6px auto;
  cursor: pointer;
  text-align: center;
}

:deep(.ant-select-single:not(.ant-select-customize-input) .ant-select-selector) {
  width: 100%;
  height: 44px !important;
  padding: 0 11px;
}

:deep(.ant-select-single:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-search-input) {
  height: 40px;
  line-height: 40px;
}

:deep(:where(.css-dev-only-do-not-override-12unj27).ant-tabs >.ant-tabs-nav .ant-tabs-nav-wrap, :where(.css-dev-only-do-not-override-12unj27).ant-tabs >div>.ant-tabs-nav .ant-tabs-nav-wrap) {
  position: relative;
  display: flex;
  flex: auto;
  align-self: stretch;
  overflow: hidden;
  white-space: nowrap;
  justify-content: center;
  transform: translate(0);
}

:deep(:where(.css-dev-only-do-not-override-12unj27).ant-tabs .ant-tabs-tab) {
  position: relative;
  display: inline-flex;
  align-items: center;
  padding: 12px 25px;
  font-size: 14px;
  background: transparent;
  border: 0;
  outline: none;
  cursor: pointer;
}
:deep(.ant-select-single .ant-select-selector .ant-select-selection-placeholder) {
  line-height: 40px;
}
</style>